﻿using ProTrack.Entity;
using ProTrack.IRepository;
using ProTrack.IServices.MasterData;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace ProTrack.Services.MasterData
{
    public class UnitMeasureServices : IUnitMeasureServices
    {
        public UnitMeasureServices(IBaseRepository db)
        {
            Db = db;
        }

        public IBaseRepository Db { get; }

        public async Task<bool> AddAsync(UnitMeasure model)
        {

            var result = await Db.InsertAsync(model);
            return result;
        }

        public async Task<bool> DeleteAsync(int[] Ids)
        {

            string sql = "delete UnitMeasure where Id in @Ids";
            var result = await Db.DeleteAsync(sql,new { Ids});
            return result;
        }

        public async Task<bool> DeleteAsync(int Id)
        {
            string sql = "delete UnitMeasure where Id = @Id";
            var result = await Db.DeleteAsync(sql, new { Id });
            return result;
        }

        public async Task<IEnumerable<UnitMeasure>> GetAsync(int PageIndex, int PageSize, string MeasureCode, string MeasureName)
        {
            string sql = "select * from UnitMeasure where 1=1 ";
            if (!string.IsNullOrEmpty(MeasureCode))
            {
                sql += " and MeasureCode like @MeasureCode ";
            }

            if (!string.IsNullOrEmpty(MeasureName))
            {
                sql += " and MeasureName like @MeasureName ";
            }

            sql += " order by CreateTime desc offset @PageSize*(@PageIndex-1) row fetch next @PageSize rows only ";



            var list = await Db.QueryAsync<UnitMeasure>(sql,new { PageIndex, PageSize, MeasureCode=$"%{MeasureCode}%", MeasureName=$"%{MeasureName}%" });
            return list;
        }

        public async Task<IEnumerable<UnitMeasure>> GetAllAsync()
        {
            string sql = "select * from UnitMeasure where EnableFlag='Y' ";
            var list = await Db.QueryAllAsync<UnitMeasure>(sql);
            return list;
        }

        public async Task<bool> UpdateAsync(UnitMeasure model)
        {
            var result = await Db.UpdateAsync(model);
            return result;
        }

        public async Task<int> GetCountAsync(string MeasureCode, string MeasureName)
        {
            string sql = "select count(*) from UnitMeasure where 1=1 ";
            if (!string.IsNullOrEmpty(MeasureCode))
            {
                sql += " and MeasureCode like @MeasureCode ";
            }

            if (!string.IsNullOrEmpty(MeasureName))
            {
                sql += " and MeasureName like @MeasureName ";
            }

            var count = await Db.GetRecoreCountAsync(sql, new { MeasureCode = $"%{MeasureCode}%", MeasureName = $"%{MeasureName}%" });
            return count;
        }
    }
}
